﻿namespace 异步方法不等于多线程
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("之前:" + Thread.CurrentThread.ManagedThreadId);
            //double r = await CalaAsync(5000);
            double r = await CalaAsync1(5000);
            Console.WriteLine(r);
            Console.WriteLine("之后:" + Thread.CurrentThread.ManagedThreadId);
            Console.Read();
        }

        static async Task<double> CalaAsync(int n)
        {
            /*Console.WriteLine("CalaAsync:" + Thread.CurrentThread.ManagedThreadId);
            Random r = new Random();
            double result = 0;
            for (int i = 0; i < n * n; i++)
            {
                result += r.NextDouble();
            }
            return result;*/
            //会扔到新的线程当中
            return await Task.Run(() =>
            {
                Console.WriteLine("CalaAsync:" + Thread.CurrentThread.ManagedThreadId);
                Random r = new Random();
                double result = 0;
                for (int i = 0; i < n * n; i++)
                {
                    result += r.NextDouble();
                }
                return result;
            });
        }

        static Task<double> CalaAsync1(int n)
        {
            //会扔到新的线程当中，且不用async
            return Task.Run(() =>
            {
                Console.WriteLine("CalaAsync:" + Thread.CurrentThread.ManagedThreadId);
                Random r = new Random();
                double result = 0;
                for (int i = 0; i < n * n; i++)
                {
                    result += r.NextDouble();
                }
                return Task.FromResult(result);
            });
        }
    }
}